﻿using System;
using System.IO;
using System.Threading;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Diagnostics;
using Microsoft.Win32;
using System.Linq;
using System.Data;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AGVUppCom
{
    public partial class Form1 : Form
    {
        int SelectModel = 0;
        public Form1(int Model)
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            SelectModel = Model;
            if (SelectModel == 0) //用户
            { 
                ControlPosition();
            }
            else if (SelectModel == 1)
            {
                ControlPosition();
            }
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        }

        /// <summary>
        /// 用户控件位置调整
        /// </summary>
        private void ControlPosition()
        {
            if (SelectModel == 0)
            {
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage4"]);
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage3"]);
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage5"]);
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage6"]);
                //MOS温度
                label87.Visible = false;
                TbxMos.Visible = false;
                label89.Visible = false;
                //当前容量
                label70.Visible = false;
                textBox_ResidualCapacity.Visible = false;
                label57.Visible = false;
                Point P1 = label70.Location;
                Point P2 = textBox_ResidualCapacity.Location;
                Point P3 = label57.Location;

                //满充容量
                label52.Visible = false;
                textBox_FullChargeCapacity.Visible = false;
                label13.Visible = false;
                label62.Location = label52.Location;
                textBox_HardwareVersion.Location = textBox_FullChargeCapacity.Location;
                //电量计充电电流
                label105.Visible = false;
                textBox11.Visible = false;
                label113.Visible = false;
                //电量计放电电流
                label107.Visible = false;
                textBox23.Visible = false;
                label114.Visible = false;
                //电量计总压
                label108.Visible = false;
                textBox26.Visible = false;
                label115.Visible = false;
                //客户代码
                label30.Visible = false;
                textBox_Producers.Visible = false;
                //循环次数位置调整
                label55.Location = P1;
                textBox_Cycles.Location = P2;
                label56.Location = P3;
                label17.Location = new Point(536, 20);
                textBox10.Location = new Point(620, 20);
                label61.Location = new Point(536, 54);
                textBox_SoftwareVersion.Location = new Point(620, 55);
            }
            else if (SelectModel == 1)
            {
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage4"]);
                //tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage3"]);
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage5"]);
                tabControl1.TabPages.Remove(tabControl1.TabPages["tabPage6"]);
                groupBox5.Visible = false;
                //MOS温度
                label87.Visible = false;
                TbxMos.Visible = false;
                label89.Visible = false;
                //当前容量
                label70.Visible = false;
                textBox_ResidualCapacity.Visible = false;
                label57.Visible = false;
                Point P1 = label70.Location;
                Point P2 = textBox_ResidualCapacity.Location;
                Point P3 = label57.Location;

                //满充容量
                label52.Visible = false;
                textBox_FullChargeCapacity.Visible = false;
                label13.Visible = false;
                label62.Location = label52.Location;
                textBox_HardwareVersion.Location = textBox_FullChargeCapacity.Location;
                //电量计充电电流
                label105.Visible = false;
                textBox11.Visible = false;
                label113.Visible = false;
                //电量计放电电流
                label107.Visible = false;
                textBox23.Visible = false;
                label114.Visible = false;
                //电量计总压
                label108.Visible = false;
                textBox26.Visible = false;
                label115.Visible = false;
                //客户代码
                label30.Visible = false;
                textBox_Producers.Visible = false;
                //循环次数位置调整
                label55.Location = P1;
                textBox_Cycles.Location = P2;
                label56.Location = P3;
                label17.Location = new Point(536, 20);
                textBox10.Location = new Point(620, 20);
                label61.Location = new Point(536, 54);
                textBox_SoftwareVersion.Location = new Point(620, 55);
                button4.Visible = false;
                button5.Visible = false;
            }
        }




        #region 十进制转十六进制(返回两个字节)
        private byte[] TenToHex(int num)
        {
            byte[] ReByte = new byte[2];
            string control = num.ToString("X2");
            string FrontCon = "";
            if (control.Length < 4)
            {
                for (int i = 0; i < 4 - control.Length; i++)
                {
                    FrontCon += "0";
                }
                control = FrontCon + control;
            }
            int a1 = Convert.ToInt32(control.Substring(0, 2), 16);
            int a2 = Convert.ToInt32(control.Substring(2, 2), 16);
            ReByte[1] = Convert.ToByte(a1);
            ReByte[0] = Convert.ToByte(a2);
            return ReByte;
        }
        #endregion
        public static bool frmDebuglogIsOpen = false;
        DelegateMethod s;
        private int DataCount = 0;   //记录数
        private bool SerialState = false;

        #region 获取可用串口
        public void GetComList()
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                this.comboBox1.Items.Clear();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    this.comboBox1.Items.Add(sValue);
                }
            }
        }
        #endregion



        #region 十六进制转十进制
        public string hextoInt16(string hex)
        {
            return Convert.ToInt32(hex, 16).ToString();
        }
        #endregion
        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists(Application.StartupPath + "/Data") == false)
            {
                Directory.CreateDirectory(Application.StartupPath + "/Data");
            }
            GetComList();
            if (comboBox1.Items.Count == 0)
            {
                MessageBox.Show("没有可使用的串口，无法连接，请检查硬件!         ", "提示");
                toolStripStatusLabel1.Text = "状态:" + "没有可使用的串口，无法连接，请检查硬件";
                toolStripStatusLabel1.ForeColor = Color.Red;
            }
            else
            {
                comboBox1.SelectedIndex = 0;
                BoundRate.SelectedIndex = 1;
                toolStripStatusLabel1.Text = "状态:" + "已经找到可以使用的串口，请确认串口信息";
                toolStripStatusLabel1.ForeColor = Color.Green;
            }
            DataSave.Checked = true;
        }

        private void Refresh_Click(object sender, EventArgs e)
        {

            GetComList();
            if (comboBox1.Items.Count == 0)
            {
                MessageBox.Show("没有可使用的串口，无法连接，请检查硬件!         ", "提示");
                toolStripStatusLabel1.Text = "状态:" + "没有可使用的串口，无法连接，请检查硬件";
                toolStripStatusLabel1.ForeColor = Color.Red;
            }
            else
            {
                comboBox1.SelectedIndex = 0;
                BoundRate.SelectedIndex = 1;
                toolStripStatusLabel1.Text = "状态:" + "已经找到可以使用的串口，请确认串口信息";
                toolStripStatusLabel1.ForeColor = Color.Green;
            }
        }
        private bool BatteryState = false;
        private void Connect_Click(object sender, EventArgs e)
        {
            try
            {
                if (Connect.Text == "打开")
                {
                    serialPort1.BaudRate = int.Parse(BoundRate.Text);
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.DataBits = 8;
                    serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    serialPort1.Parity = System.IO.Ports.Parity.None;
                    serialPort1.ReadTimeout = 6000;
                    serialPort1.Open();
                    //SendBuffer[0] = 0x7E;
                    //SendBuffer[1] = 0x12;
                    //SendBuffer[2] = 0x00;
                    //SendBuffer[3] = 0x08;
                    //SendBuffer[4] = 0x64;
                    //SendBuffer[5] = 0x03;
                    //ReadWrite(SendBuffer, 0, 6, 1);
                    //Thread.Sleep(100);
                    //if (ReadWrite(ReadBuffer, 0, 14, 2) == true)
                    //{
                    //    BatteryState = true;
                    //}
                    BatteryState = true;
                    Connect.Text = "断开";
                    Connect.ForeColor = Color.Red;
                    comboBox1.Enabled = false;
                    BoundRate.Enabled = false;
                    Connected.Visible = true;
                    DisConnected.Visible = false;
                    SerialState = true;
                }
                else
                {
                    serialPort1.Close();
                    button19_Click(null, null);
                    Connect.Text = "打开";
                    Connect.ForeColor = Color.Green;
                    comboBox1.Enabled = true;
                    BoundRate.Enabled = true;
                    Connected.Visible = false;
                    DisConnected.Visible = true;
                    SerialState = false;
                    BatteryState = false;
                    pictureBox9.Visible = false;
                    pictureBox8.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开串口失败!         ", "提示");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            LabelTime.Text = DateTime.Now.ToString();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            DataCol();
        }

        #region mos放电(开)
        private void button15_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }

            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x94;
            SendBuffer[2] = 0x00;    //MOS控制 
            SendBuffer[3] = 0x01;    // 信息长度
            SendBuffer[4] = 0x02;   //数据信息
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1); ;   //xor
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            Thread.Sleep(100);
            ReadWrite(ReadBuffer, 0, 7, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                pictureBox3.Visible = true;
                pictureBox1.Visible = false;
                MessageBox.Show("放电MOS打开成功");
            }
            else
            {
                pictureBox3.Visible = false;
                pictureBox1.Visible = true;
            }

        }
        #endregion

        #region MOS放电关
        private void button16_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x94;
            SendBuffer[2] = 0x00;    //MOS控制 (初始字节)
            SendBuffer[3] = 0x01;    // 信息长度
            SendBuffer[4] = 0x01;   //数据信息
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1); ;   //xor
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            Thread.Sleep(100);
            ReadWrite(ReadBuffer, 0, 7, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                pictureBox1.Visible = true;
                pictureBox3.Visible = false;
                MessageBox.Show("放电MOS关闭成功");
            }
            else
            {
                pictureBox1.Visible = false;
                pictureBox3.Visible = true;
            }
        }
        #endregion
        #region mos充电关
        private void button18_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x94;
            SendBuffer[2] = 0x00;    //MOS控制 (初始字节)
            SendBuffer[3] = 0x01;    // 信息长度
            SendBuffer[4] = 0x04;   //数据信息
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1);   //xor
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            Thread.Sleep(100);
            ReadWrite(ReadBuffer, 0, 7, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                pictureBox4.Visible = true;
                pictureBox2.Visible = false;
                MessageBox.Show("充电MOS关闭成功");
            }
            else
            {
                pictureBox4.Visible = false;
                pictureBox2.Visible = true;
            }

        }
        #endregion

        #region mos充电开
        private void button17_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x94;
            SendBuffer[2] = 0x00;    //MOS控制 (初始字节)
            SendBuffer[3] = 0x01;    // 信息长度
            SendBuffer[4] = 0x08;   //数据信息
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1); ;   //xor
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            Thread.Sleep(120);
            ReadWrite(ReadBuffer, 0, 7, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                pictureBox2.Visible = true;
                pictureBox4.Visible = false;
                MessageBox.Show("充电MOS打开成功");

            }
            else
            {
                pictureBox2.Visible = false;
                pictureBox4.Visible = true;
            }
        }
        #endregion
        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }
        FileStream fs = null;
        StreamWriter srWrite = null;
        private Thread DataReceiveThread;
        private void button1_Click(object sender, EventArgs e)
        {

            if (SerialState == false)
            {
                MessageBox.Show("串口未打开!");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误!");
                return;
            }
            if (SerialState == true && BatteryState == true)
            {
                numericUpDown1.Enabled = false;
                string FileName = DateTime.Now.ToString("yyyy-MM-dd HH");
                string Path = Application.StartupPath + @"\Data" + string.Format(@"\{0}.txt", FileName);
                if (!File.Exists(Path))
                {
                    fs = new FileStream(Path, FileMode.Append, FileAccess.Write);
                    srWrite = new StreamWriter(fs);
                    if (SelectModel == 0 || SelectModel == 1)
                    {
                        srWrite.WriteLine(@"记录时间,产品序号,V01,V02,V03,V04,V05,V06,V07,V08,总压,最高电压,最低电压,温度点1,温度点2,充电电流,放电电流,设计容量,soc,循环次数,状态信息1,状态信息2");
                    }
                    else
                    {
                        srWrite.WriteLine(@"记录时间,产品序号,V01,V02,V03,V04,V05,V06,V07,V08,总压,最高电压,最低电压,温度点1,温度点2,MOS温度,充电电流,放电电流,设计容量,soc,当前容量,循环次数,状态信息1,状态信息2");
                    }
                    srWrite.Flush();
                }
                else
                {
                    fs = new FileStream(Path, FileMode.Append, FileAccess.Write);
                    srWrite = new StreamWriter(fs);
                }
                CollectData(true);
                timer3.Interval = (int)numericUpDown1.Value * 1000;
                timer3.Enabled = true;
                button1.Enabled = false;
                numericUpDown1.Enabled = false;
                timer3.Start();
            }
        }
        byte[] SendBuffer = new byte[15];
        byte[] ReadBuffer = new byte[45];
        byte[] DataWrite = new byte[134];

        int CollectFlag = 0;
        private bool CollectData(bool flag)
        {
            try
            {
                CollectFlag = 1;
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x10;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x1C;
                SendBuffer[4] = 0x72;
                SendBuffer[5] = 0x03;

                if (ReadWrite(SendBuffer, 0, 6, 1) == false)
                {
                    return false; ;
                }
                Thread.Sleep(100);
                if (ReadWrite(ReadBuffer, 0, 34, 2) == false)
                {
                    return false;
                }
                if (Check(ReadBuffer.Skip(0).Take(32).ToArray(), ReadBuffer[32]) == true)
                {
                    #region V1
                    textBox1.Text = hextoInt16(ReadBuffer[5].ToString("X2") + ReadBuffer[4].ToString("X2"));
                    #endregion

                    #region v2
                    textBox2.Text = hextoInt16(ReadBuffer[7].ToString("X2") + ReadBuffer[6].ToString("X2"));
                    #endregion

                    #region v3
                    textBox3.Text = hextoInt16(ReadBuffer[9].ToString("x2") + ReadBuffer[8].ToString("x2"));
                    #endregion

                    #region v4
                    textBox4.Text = hextoInt16(ReadBuffer[11].ToString("x2") + ReadBuffer[10].ToString("x2"));
                    #endregion

                    #region v5
                    textBox5.Text = hextoInt16(ReadBuffer[13].ToString("x2") + ReadBuffer[12].ToString("x2"));
                    #endregion

                    #region v6
                    textBox6.Text = hextoInt16(ReadBuffer[15].ToString("x2") + ReadBuffer[14].ToString("x2"));
                    #endregion

                    #region v7
                    textBox7.Text = hextoInt16(ReadBuffer[17].ToString("x2") + ReadBuffer[16].ToString("x2"));
                    #endregion

                    #region v8
                    textBox8.Text = hextoInt16(ReadBuffer[19].ToString("x2") + ReadBuffer[18].ToString("x2"));
                    #endregion;

                    #region 总压
                    textBox_PACKVoltage.Text = hextoInt16(ReadBuffer[21].ToString("x2") + ReadBuffer[20].ToString("x2"));
                    #endregion;

                    #region 最高电压
                    textBox_MaximumVoltage.Text = hextoInt16(ReadBuffer[23].ToString("x2") + ReadBuffer[22].ToString("x2"));
                    #endregion

                    #region 最低电压
                    textBox_MinimumVoltage.Text = hextoInt16(ReadBuffer[25].ToString("x2") + ReadBuffer[24].ToString("x2"));
                    #endregion

                    #region 电压差
                    textBox_DropoutVoltage.Text = (int.Parse(textBox_MaximumVoltage.Text.ToString()) - int.Parse(textBox_MinimumVoltage.Text.ToString())).ToString();
                    #endregion

                    #region 温度点一
                    string Value = hextoInt16(ReadBuffer[27].ToString("x2") + ReadBuffer[26].ToString("x2"));
                    textBox_BatteryModel.Text = (double.Parse(Value) / 100.00).ToString();
                    #endregion

                    #region 温度点二
                    Value = hextoInt16(ReadBuffer[29].ToString("x2") + ReadBuffer[28].ToString("x2"));
                    textBox_BatteriesModels.Text = (double.Parse(Value) / 100.00).ToString();
                    #endregion

                    #region 温度点三
                    Value = hextoInt16(ReadBuffer[31].ToString("x2") + ReadBuffer[30].ToString("x2"));
                    TbxMos.Text = (double.Parse(Value) / 100.00).ToString();
                    #endregion
                }
                #region 0x11指令
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x11;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x15;
                SendBuffer[4] = 0x7A;
                SendBuffer[5] = 0x03;
                byte[] a2 = new byte[34];
                if (ReadWrite(SendBuffer, 0, 6, 1) == false)
                {
                    return false;
                }
                Thread.Sleep(100);
                if (ReadWrite(a2, 0, 27, 2) == false)
                {
                    return false;
                }
                string StatusMessage1 = "";
                string StatusMessage2 = "";
                if (Check(a2.Skip(0).Take(25).ToArray(), a2[25]) == true)
                {
                    #region 充电电流
                    string Value = hextoInt16(a2[5].ToString("x2") + a2[4].ToString("x2"));
                    textBox_Current.Text = (int.Parse(Value) * 10).ToString();
                    #endregion

                    #region 放电电流
                    Value = hextoInt16(a2[7].ToString("x2") + a2[6].ToString("x2"));
                    textBox_Temp.Text = (int.Parse(Value) * 10).ToString();
                    #endregion
                    string ddd = a2[9].ToString("x2") + a2[8].ToString("x2");
                    string WarningInfo = Strtwo(0x00, hextoInt16(ddd), 2, 16);
                    char[] WarnChar = WarningInfo.ToArray();

                    #region 高压告警
                    if (WarnChar[15] == '1')
                    {
                        pictureBoxS1.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS1.BackColor = Color.Green;
                    }
                    #endregion

                    #region 低压告警
                    if (WarnChar[14] == '1')
                    {
                        pictureBoxS2.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS2.BackColor = Color.Green;
                    }
                    #endregion

                    #region 充电过流告警
                    if (WarnChar[13] == '1')
                    {
                        pictureBoxS3.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS3.BackColor = Color.Green;
                    }
                    #endregion

                    #region 放电过流告警
                    if (WarnChar[12] == '1')
                    {
                        pictureBoxS4.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS4.BackColor = Color.Green;
                    }
                    #endregion

                    #region 充电高温告警
                    if (WarnChar[11] == '1')
                    {
                        pictureBoxS5.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS5.BackColor = Color.Green;
                    }
                    #endregion

                    #region 充电低温告警
                    if (WarnChar[10] == '1')
                    {
                        pictureBoxS6.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS6.BackColor = Color.Green;
                    }
                    #endregion

                    #region 放电高温告警
                    if (WarnChar[9] == '1')
                    {
                        pictureBoxS7.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS7.BackColor = Color.Green;
                    }
                    #endregion

                    #region 放电低温告警
                    if (WarnChar[8] == '1')
                    {
                        pictureBoxS8.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS8.BackColor = Color.Green;
                    }
                    #endregion

                    #region 短路保护
                    if (WarnChar[7] == '1')
                    {
                        pictureBoxS9.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS9.BackColor = Color.Green;
                    }
                    #endregion

                    #region MOS温度高
                    if (WarnChar[6] == '1')
                    {
                        pictureBox10.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox10.BackColor = Color.Green;
                    }
                    #endregion

                    Array.Reverse(WarnChar);
                    StatusMessage1 = new string(WarnChar);

                    ddd = a2[11].ToString("X2") + a2[10].ToString("X2");
                    WarnChar = Strtwo(0x00, hextoInt16(ddd), 2, 16).ToArray();
                    #region 电压采集点断线
                    if (WarnChar[15] == '1')
                    {
                        pictureBoxS10.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxS10.BackColor = Color.Green;
                    }
                    #endregion

                    #region 温度采集点断线
                    if (WarnChar[14] == '1')
                    {
                        pictureBox5.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox5.BackColor = Color.Green;
                    }
                    #endregion

                    #region 通讯异常
                    if (WarnChar[13] == '1')
                    {
                        pictureBox6.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox6.BackColor = Color.Green;
                    }
                    #endregion

                    #region 电量计通讯异常
                    if (WarnChar[12] == '1')
                    {
                        pictureBox7.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox7.BackColor = Color.Green;
                    }
                    #endregion

                    #region mos管充电状态
                    if (WarnChar[11] == '1')
                    {
                        pictureBoxBattery1.BackColor = Color.Red;

                    }
                    else
                    {
                        pictureBoxBattery1.BackColor = Color.Green;
                    }

                    #endregion

                    #region mos管放电状态
                    if (WarnChar[10] == '1')
                    {
                        pictureBoxBattery2.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBoxBattery2.BackColor = Color.Green;
                    }
                    #endregion

                    #region 预充电MOS状态
                    if (WarnChar[9] == '1')
                    {
                        pictureBox11.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox11.BackColor = Color.Green;
                    }
                    #endregion

                    #region 时钟异常
                    if (WarnChar[8] == '1')
                    {
                        pictureBox12.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox12.BackColor = Color.Green;
                    }
                    #endregion

                    #region EEPROM异常
                    if (WarnChar[7] == '1')
                    {
                        pictureBox13.BackColor = Color.Red;
                    }
                    else
                    {
                        pictureBox13.BackColor = Color.Green;
                    }
                    #endregion
                    Array.Reverse(WarnChar);
                    StatusMessage2 = new string(WarnChar);

                    #region SOC
                    textBox_RelativeSOC.Text = a2[12].ToString();
                    #endregion

                    #region 当前容量
                    textBox_ResidualCapacity.Text = hextoInt16(a2[14].ToString("x2") + a2[13].ToString("x2"));
                    #endregion

                    #region 满充容量
                    textBox_FullChargeCapacity.Text = hextoInt16(a2[16].ToString("x2") + a2[15].ToString("x2"));
                    #endregion

                    #region 循环次数
                    textBox_Cycles.Text = hextoInt16(a2[18].ToString("x2") + a2[17].ToString("x2"));
                    #endregion

                    #region 电量计充电电流
                    Value = hextoInt16(a2[20].ToString("x2") + a2[19].ToString("x2"));
                    textBox11.Text = (int.Parse(Value) * 10).ToString();
                    #endregion

                    #region 电量计放电电流
                    Value = hextoInt16(a2[22].ToString("x2") + a2[21].ToString("x2"));
                    textBox23.Text = (int.Parse(Value) * 10).ToString();
                    #endregion

                    #region 电量计总压
                    textBox26.Text = hextoInt16(a2[24].ToString("x2") + a2[23].ToString("x2"));
                    #endregion

                }
                #endregion

                #region 0x12
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x12;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x08;
                SendBuffer[4] = 0x64;
                SendBuffer[5] = 0x03;
                if (ReadWrite(SendBuffer, 0, 6, 1) == false)
                {
                    return false;
                }
                byte[] a3 = new byte[34];
                Thread.Sleep(100);
                if (ReadWrite(a3, 0, 34, 2) == false)
                {
                    return false;
                }
                if (Check(a3.Skip(0).Take(12).ToArray(), a3[12]) == true)
                {
                    #region 客户代码
                    // textBox_Producers.Text = a3[4].ToString();
                    #endregion

                    #region 产品序号
                    textBox10.Text = hextoInt16(a3[6].ToString("x2") + a3[5].ToString("x2"));
                    #endregion

                    #region 设计容量
                    textBox_DesignCapacity.Text = hextoInt16(a3[8].ToString("x2") + a3[7].ToString("x2"));
                    #endregion

                    #region 软件版本
                    textBox_SoftwareVersion.Text = "A" + a3[9].ToString();
                    #endregion

                    #region 硬件版本
                    textBox_HardwareVersion.Text = "A" + a3[10].ToString();
                    #endregion
                }
                if (DataSave.Checked == true)
                {
                    string LogMessage = "";
                    if (SelectModel == 0 || SelectModel == 1)
                    {
                        LogMessage = string.Format(@"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21}",
                           DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss"), textBox10.Text, textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, textBox_PACKVoltage.Text, textBox_MaximumVoltage.Text, textBox_MinimumVoltage.Text, textBox_BatteryModel.Text, textBox_BatteriesModels.Text, textBox_Current.Text, textBox_Temp.Text, textBox_DesignCapacity.Text, textBox_RelativeSOC.Text, textBox_Cycles.Text, StatusMessage1, StatusMessage2);
                    }
                    else
                    {
                        LogMessage = string.Format(@"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}",
                          DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss"), textBox10.Text, textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, textBox_PACKVoltage.Text, textBox_MaximumVoltage.Text, textBox_MinimumVoltage.Text, textBox_BatteryModel.Text, textBox_BatteriesModels.Text, TbxMos.Text, textBox_Current.Text, textBox_Temp.Text, textBox_DesignCapacity.Text, textBox_RelativeSOC.Text, textBox_ResidualCapacity.Text, textBox_Cycles.Text, StatusMessage1, StatusMessage2);
                    }
                    srWrite.WriteLine(LogMessage);
                    srWrite.Flush();
                    DataCount++;
                    label76.Text = DataCount.ToString();
                }

                
            }
            catch(Exception ex)
            {

            }
            return true;
        }
        #endregion

        #region 检测校验
        private bool Check(byte[] DataBuffer, byte Target)
        {
            byte Contrast = new byte();
            for (int i = 0; i < DataBuffer.Length; i++)
            {
                Contrast ^= DataBuffer[i];
            }
            if (Contrast == Target)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 返回校验码
        private byte ReturnByte(byte[] ByteArray, int flag)
        {
            byte Control = new byte();
            if (flag == 1)
            {
                for (int i = 0; i < ByteArray.Length; i++)
                {
                    Control ^= ByteArray[i];
                }
            }
            else
            {
                for (int i = 0; i < ByteArray.Length; i++)
                {
                    Control += ByteArray[i];
                }
            }
            return Control;
        }
        #endregion

        #region byte转二进制
        private string Strtwo(byte buffer, string hex, int flag, int binNUm)
        {
            string control = "";
            if (flag == 2)
            {
                control = Convert.ToString(int.Parse(hex), 2);
                if (control.Length < binNUm)
                {
                    int AddLenght = binNUm - control.Length;
                    string ReStr = "";
                    for (int i = 0; i < AddLenght; i++)
                    {
                        ReStr += "0";
                    }
                    control = ReStr + control;
                }
            }
            else if (flag == 1)
            {
                control = Convert.ToString(buffer, 2);
                if (control.Length < binNUm)
                {
                    int AddLenght = binNUm - control.Length;
                    string ReStr = "";
                    for (int i = 0; i < AddLenght; i++)
                    {
                        ReStr += "0";
                    }
                    control = ReStr + control;
                }
            }
            return control;
        }

        #endregion

        #region 单体电压
        private void button14_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox22.Text))
            {
                MessageBox.Show("请输入单体电压的值");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x81;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x03;
            SendBuffer[4] = 0x01;  //单体电压校准
            byte[] DataByte = TenToHex(int.Parse(textBox22.Text.Trim()));
            SendBuffer[5] = DataByte[0];
            SendBuffer[6] = DataByte[1];
            SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1);
            SendBuffer[8] = 0x03;
            ReadWrite(SendBuffer, 0, 9, 1);
            Thread.Sleep(200);
            ReadWrite(ReadBuffer, 0, 8, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                MessageBox.Show("校准单体电压成功!");
            }
            else
            {
                MessageBox.Show("校准单体电压失败!");
            }
        }
        #endregion

        #region 总压校准
        private void button13_Click(object sender, EventArgs e)
        {

            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox21.Text))
            {
                MessageBox.Show("请输入总压的值");
                return;
            }
            else
            {
                try
                {
                    SendBuffer[0] = 0x7E;
                    SendBuffer[1] = 0x81;
                    SendBuffer[2] = 0x00;
                    SendBuffer[3] = 0x03;
                    SendBuffer[4] = 0x02; //总压校准
                    byte[] DataByte = TenToHex(int.Parse(textBox21.Text));
                    SendBuffer[5] = DataByte[0];
                    SendBuffer[6] = DataByte[1];
                    SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1); //校验码
                    SendBuffer[8] = 0x03;
                    ReadWrite(SendBuffer, 0, 9, 1);
                    Thread.Sleep(5000);
                    if (ReadWrite(ReadBuffer, 0, 8, 2) == true)
                    {
                        MessageBox.Show("总压校准成功!");
                    }

                }
                catch
                {
                    MessageBox.Show("总压校准失败");
                    return;
                }

            }
        }
            
            
        
        #endregion
        #region 温度校准
        private void button7_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox_Temp.Text))
            {
                MessageBox.Show("请输入温度的值");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x81;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x03;
            SendBuffer[4] = 0x04; //温度校准
            int WenDU = int.Parse(textBox15.Text.ToString()) * 100;
            byte[] DataByte = TenToHex(WenDU);
            SendBuffer[5] = DataByte[0];
            SendBuffer[6] = DataByte[1];
            SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1); //校验码
            SendBuffer[8] = 0x03;
            ReadWrite(SendBuffer, 0, 9, 1);
            Thread.Sleep(200);
            ReadWrite(ReadBuffer, 0, 8, 2);
            //if (Check(ReadBuffer.Skip(0).Take(5).ToArray(), ReadBuffer[5]) == true)
            //{
            //    string AloneCell = Strtwo(ReadBuffer[4], null, 1, 8);
            //    char[] AloneCellArray = AloneCell.ToArray();   //二进制转换字符数组
            //    if (AloneCellArray.Count(c => c == '1') == 1)
            //    {
            //        if (AloneCellArray[5] == '1')
            //        {
            //            MessageBox.Show("温度校准成功!");
            //            return;
            //        }
            //        else
            //        {
            //            MessageBox.Show("温度校准失败!");
            //            return;
            //        }
            //    }
            //}
            if (ReadBuffer[4] == 0xAA)
            {
                MessageBox.Show("温度校准成功!");
            }
            else
            {
                MessageBox.Show("温度校准失败!");
                return;
            }
        }
        #endregion
        /// 延时函数
        /// </summary>
        /// <param name="delayTime">需要延时多少秒</param>
        /// <returns></returns>
        public static void Delay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)
            {
                Application.DoEvents();
            }
        }
        #region 电流校准
        private void button9_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox17.Text))
            {
                MessageBox.Show("请输入电流的值");
                return;
            }
            else
            {
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x81;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x03;
                SendBuffer[4] = 0x08; //电流校准
                byte[] DataByte = TenToHex(int.Parse(textBox17.Text.ToString()) / 10);
                SendBuffer[5] = DataByte[0];
                SendBuffer[6] = DataByte[1];
                SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1); //校验码
                SendBuffer[8] = 0x03;
                ReadWrite(SendBuffer, 0, 9, 1);
                Thread.Sleep(500);
                if(ReadWrite(ReadBuffer, 0, 8, 2) == true)
                {
                    MessageBox.Show("电流校准成功!");
                }
                //if (Check(ReadBuffer.Skip(0).Take(5).ToArray(), ReadBuffer[5]) == true)
                //{
                //    string AloneCell = Strtwo(ReadBuffer[4], null, 1, 8);
                //    char[] AloneCellArray = AloneCell.ToArray();   //二进制转换字符数组
                //    if (AloneCellArray.Count(c => c == '1') == 1)
                //    {
                //        if (AloneCellArray[4] == '1')
                //        {
                //            MessageBox.Show("电流校准成功!");
                //        }
                //    }
                //    else
                //    {
                //        MessageBox.Show("电流校准失败!");
                //    }
                //}
                else
                {
                    MessageBox.Show("电流校准失败!");
                }
            }
        }

        #endregion

        #region 设计容量
        private void button12_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox20.Text))
            {
                MessageBox.Show("请输入设计容量的值");
                return;
            }
            else
            {
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x81;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x03;
                SendBuffer[4] = 0x10; //设计容量
                byte[] DataByte = TenToHex(int.Parse(textBox20.Text));
                SendBuffer[5] = DataByte[0];
                SendBuffer[6] = DataByte[1];
                SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1); //校验码
                SendBuffer[8] = 0x03;
                ReadWrite(SendBuffer, 0, 9, 1);
                Thread.Sleep(200);
                ReadWrite(ReadBuffer, 0, 8, 2);
                //if (Check(ReadBuffer.Skip(0).Take(5).ToArray(), ReadBuffer[5]) == true)
                //{
                //    string AloneCell = Strtwo(ReadBuffer[4], null, 1, 8);
                //    char[] AloneCellArray = AloneCell.ToArray();   //二进制转换字符数组
                //    var CountNum = from v in AloneCellArray where v == 1 select v;
                //    if (AloneCellArray.Count(c => c == '1') == 1)
                //    {
                //        if (AloneCellArray[3] == '1')
                //        {
                //            MessageBox.Show("设计容量校准成功!");
                //        }
                //        else
                //        {
                //            MessageBox.Show("设计容量校准失败!");
                //        }
                //    }
                //}
                if (ReadBuffer[4] == 0xAA)
                {
                    MessageBox.Show("设计容量校准成功!");
                }
                else
                {
                    MessageBox.Show("设计容量校准失败!");
                }
            }
        }

        #endregion

        #region 产品序号
        private void button8_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox16.Text))
            {
                MessageBox.Show("请输入产品序号");
                return;
            }
            else
            {
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x81;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x03;
                SendBuffer[4] = 0x20; //产品序号
                byte[] Databyte = TenToHex(int.Parse(textBox16.Text.ToString()));
                SendBuffer[5] = Databyte[0];
                SendBuffer[6] = Databyte[1];
                SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1); //校验码
                SendBuffer[8] = 0x03;
                ReadWrite(SendBuffer, 0, 9, 1);
                Delay(100);
                ReadWrite(ReadBuffer, 0, 8, 2);
                //if (Check(ReadBuffer.Skip(0).Take(5).ToArray(), ReadBuffer[5]) == true)
                //{

                //    string AloneCell = Strtwo(ReadBuffer[4], null, 1, 8);
                //    char[] AloneCellArray = AloneCell.ToArray();   //二进制转换字符数组
                //    var CountNum = from v in AloneCellArray where v == 1 select v;
                //    if (AloneCellArray.Count(c => c == '1') == 1)
                //    {
                //        if (AloneCellArray[2] == '1')
                //        {
                //            MessageBox.Show("产品序号设置成功!");
                //        }
                //        else
                //        {
                //            MessageBox.Show("产品序号设置失败!");
                //        }
                //    }
                //}
                if (ReadBuffer[4] == 0xAA)
                {
                    MessageBox.Show("产品序号设置成功!");
                }
                else
                {
                    MessageBox.Show("产品序号设置失败!");
                }
            }
        }
        #endregion

        private void DataSave_CheckedChanged(object sender, EventArgs e)
        {
            if (DataSave.Checked == true)
            {
                textBox27.Text = Application.StartupPath + @"\Data";
            }
            else
            {
                textBox27.Text = "";
            }
        }

        #region 按时间隔触发采取数据函数
        private void timer3_Tick(object sender, EventArgs e)
        {
            //报错也不停止采集
            if (CollectData(true) == false&& CollectFlag==1)
            {
                timer3.Stop();
                button1.Enabled = true;
                numericUpDown1.Enabled = true;
                srWrite.Close();
                fs.Close();
                MessageBox.Show(messInfo);
            }
        }
        #endregion

        #region 停止采集
        private void button19_Click(object sender, EventArgs e)
        {
            if (button1.Enabled == false)
            {
                CollectFlag = 0;
                timer3.Stop();
                button1.Enabled = true;
                numericUpDown1.Enabled = true;
                srWrite.Close();
                fs.Close();
            }
        }
        #endregion

        #region 打开调试窗口
        private void button5_Click(object sender, EventArgs e)
        {
            frmDebug frm = new frmDebug();
            s = frm.ChangeTime;
            frm.Show();
            frmDebuglogIsOpen = true;

        }
        #endregion
        private void EventReturnDebug(string DeBugText)
        {
            if (frmDebuglogIsOpen == true)
            {
                s(DeBugText);
            }
        }
        private bool ReadWrite(byte[] buffer, int offset, int count, int flag)
        {
            string DebugText = "";
            try
            {
                //write
                if (flag == 1)
                {

                    serialPort1.Write(buffer, offset, count);
                    //string data = "";
                    StringBuilder data2 = new StringBuilder();
                    for (int i = 0; i < count; i++)
                    {
                        //data += "  " + buffer[i].ToString("x2").ToUpper();
                        data2.Append(buffer[i].ToString("x2").ToUpper()).Append(" ");
                    }
                    DebugText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss  ") + "发送:" + data2;
                    EventReturnDebug(DebugText);
                    return true;
                }
                //read
                if (flag == 2)
                {

                    serialPort1.Read(buffer, offset, count);
                    BatteryState = true;
                    //string data = "";
                    StringBuilder data2 = new StringBuilder();
                    for (int i = 0; i < count; i++)
                    {
                       // data += "  " + buffer[i].ToString("x2").ToUpper();l
                        data2.Append(buffer[i].ToString("x2").ToUpper()).Append(" ");
                    }
                    DebugText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss  ") + "接收:" + data2;
                    EventReturnDebug(DebugText);
                    pictureBox9.Visible = true;
                    pictureBox8.Visible = false;
                    serialPort1.DiscardInBuffer();
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                pictureBox9.Visible = false;
                pictureBox8.Visible = true;
                messInfo = ex.Message;
                return false;
            }
        }
        private string messInfo = "";
        private byte[] byteRemaNum;  //文件字节流
        private int DataNum = 0;     //包数
        private List<byte[]> BinArray = new List<byte[]>();  //字节分组
        private void button2_Click(object sender, EventArgs e)
        {
            BinArray.Clear();
            progressBar1.Value = 0;
            label22.Text = "0";
            label86.Text = "0";
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.Filter = "文档(*.bin/*.hex)|*bin;*hex";
            if (openfile.ShowDialog() == DialogResult.OK)
            {
                textBox13.Text = openfile.FileName;
                FileStream fBin = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read);
                int length = (int)fBin.Length;
                byte[] BinBuffer = new byte[length];
                BinaryReader ReadBin = new BinaryReader(fBin);
                BinBuffer = ReadBin.ReadBytes(length);
                byte[] SecondBuffer;
                if (System.Text.Encoding.ASCII.GetString(BinBuffer, 0, 10) == "encryption") //加密
                {
                    SecondBuffer = new byte[BinBuffer.Length - 10];
                    //解密
                    for (int i = 10; i < BinBuffer.Length; i++)
                    {
                        BinBuffer[i] ^= 0x45;
                    }
                    Buffer.BlockCopy(BinBuffer, 10, SecondBuffer, 0, SecondBuffer.Length);
                }
                else
                {
                    SecondBuffer = new byte[BinBuffer.Length];
                    Buffer.BlockCopy(BinBuffer, 0, SecondBuffer, 0, SecondBuffer.Length);
                }
                if (SecondBuffer.Length % 128 != 0)   //不够后面补零
                {
                    int RemaNum = SecondBuffer.Length % 128;
                    int AddNum = 128 - RemaNum;
                    byteRemaNum = new byte[SecondBuffer.Length + AddNum];
                    Buffer.BlockCopy(SecondBuffer, 0, byteRemaNum, 0, SecondBuffer.Length);
                    DataNum = byteRemaNum.Length / 128;
                    label20.Text = DataNum.ToString();
                }
                else
                {
                    byteRemaNum = new byte[SecondBuffer.Length];
                    Buffer.BlockCopy(SecondBuffer, 0, byteRemaNum, 0, SecondBuffer.Length);
                    DataNum = byteRemaNum.Length / 128;
                    label20.Text = DataNum.ToString();
                }
                progressBar1.Maximum = DataNum;
                for (int i = 0; i < DataNum; i++)
                {
                    int DataOrderNUm = i * 128;
                    byte[] Conter = new byte[128];
                    Buffer.BlockCopy(byteRemaNum, DataOrderNUm, Conter, 0, 128);
                    BinArray.Add(Conter);
                }
                MessageBox.Show("打开文件成功!");
            }
        }

        #region 开始升级
        private void button3_Click(object sender, EventArgs e)
        {
            Task t1 = Task.Factory.StartNew(() =>
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    if (SerialState == false)
                    {
                        MessageBox.Show("串口未打开");
                        return;
                    }
                    if (BinArray.Count <= 0 || BinArray == null)
                    {
                        MessageBox.Show("请选择升级的文件");
                        return;
                    }
                    button19_Click(null, null);
                    IsCancel = false;
                    label22.Text = "0";
                    label86.Text = "0";
                    progressBar1.Value = 0;
                    button3.Enabled = false;
                    bool flagSuess = UpdateFun();
                    sw.Stop();
                    TimeSpan ts = sw.Elapsed;
                    if (flagSuess == true)
                    {
                        MessageBox.Show(string.Format("升级成功用了{0}ms", ts.TotalMilliseconds));
                    }
                    else if (flagSuess == false && IsCancel == false)
                    {
                        MessageBox.Show("升级失败");
                    }
                    if (IsCancel == true && flagSuess == false)
                    {
                        MessageBox.Show("已取消升级!");
                    }
                    button3.Enabled = true;
                    serialPort1.BaudRate = 9600;
                    progressBar1.Value = 0;
                }
                catch (Exception ex)
                {
                    button3.Enabled = true;
                    MessageBox.Show(ex.Message);
                    return;
                }
            });
        }
        #endregion

        #region 累加和取低位一字节
        private byte SumByteBot(byte[] Soc)
        {
            byte bb = new byte();
            int kk = 0;
            for (int i = 0; i < Soc.Length; i++)
            {
                kk += Soc[i];
            }
            int Remainder = kk % 256;
            if (Remainder == 0)
            {
                bb = 0x00;
            }
            else
            {
                bb = Convert.ToByte(Remainder);
            }
            return bb;
        }
        #endregion

        #region 发送数据过程
        private bool Meddle(int i)
        {

            DataWrite[0] = 0x7E;
            DataWrite[1] = 0x84;
            DataWrite[2] = 0x82;
            int aa = i + 1;
            //两字节序号
            if (aa > 255)
            {
                string bytecon = aa.ToString("X4").ToUpper();
                int a1 = Convert.ToInt16(bytecon.Substring(2, 2), 16);
                int a2 = Convert.ToInt16(bytecon.Substring(0, 2), 16);
                DataWrite[3] = Convert.ToByte(a1);
                DataWrite[4] = Convert.ToByte(a2);
            }
            else
            {
                DataWrite[3] = Convert.ToByte(aa);
                DataWrite[4] = 0x00;
            }
            Buffer.BlockCopy(BinArray[i], 0, DataWrite, 5, 128);
            DataWrite[133] = SumByteBot(DataWrite.Take(133).ToArray());
            ReadWrite(DataWrite, 0, 134, 1);
            label22.Text = aa.ToString();
            //Thread.Sleep(200);
            ReadWrite(ReadBuffer, 0, 6, 2);
            if (ReadBuffer[0] == 0xff)
            {
                label86.Text = aa.ToString();
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 升级函数
        private bool UpdateFun()
        {
            //请求升级指令
            for (int i = 0; i < 10; i++)
            {
                serialPort1.BaudRate = 9600;
                SendBuffer[0] = 0x7E;   //写指令
                SendBuffer[1] = 0x82;   //请求码
                SendBuffer[2] = 0x00;   //字节序号
                SendBuffer[3] = 0x02;   //信息长度
                SendBuffer[4] = 0xA5;
                SendBuffer[5] = 0xA5;
                SendBuffer[6] = ReturnByte(SendBuffer.Skip(0).Take(6).ToArray(), 1);   //校验码
                SendBuffer[7] = 0x03;
                ReadWrite(SendBuffer, 0, 8, 1);
                Thread.Sleep(100);
                serialPort1.BaudRate = 38400;
                // Thread.Sleep(1000);  //休眠2秒
                ReadWrite(ReadBuffer, 0, 8, 2);
                if (ReadBuffer[0] == 0xff)
                {
                    break;
                }
                if (i == 9)
                {
                    return false;
                }
            }
            if (ReadBuffer[0] == 0xFF)
            {
                int sendCount = 0;
                //发送包数
                int oiue = 0;
                for (int i = 0; i < 3; i++)
                {
                    sendCount++;
                    SendBuffer[0] = 0x7E; //写标志
                    SendBuffer[1] = 0x83; //指令码
                    SendBuffer[2] = 0x02; //信息长度
                    SendBuffer[3] = Convert.ToByte(DataNum);
                    SendBuffer[4] = 0x00;
                    SendBuffer[5] = ReturnByte(SendBuffer.Take(5).ToArray(), 2);
                    ReadWrite(SendBuffer, 0, 6, 1);
                    //Thread.Sleep(100);
                    ReadWrite(ReadBuffer, 0, 6, 2);
                    if (ReadBuffer[0] == 0xff)//FF正确，1F错误
                    {
                        for (int j = 0; j < DataNum; j++)   //发送数据包
                        {
                            Application.DoEvents();
                            for (int k = 0; k < 3; k++)
                            {
                                bool flagBreak = Meddle(j);
                                if (flagBreak == true)
                                {
                                    progressBar1.Value++;
                                    break;
                                }
                                else
                                {
                                    oiue++;
                                }
                                if (oiue == 3)
                                {
                                    return false;
                                }
                            }
                            if (IsCancel == true)
                            {
                                return false;
                            }
                        }
                        //发送完成，升级结束
                        SendBuffer[0] = 0x7E;
                        SendBuffer[1] = 0x83;
                        SendBuffer[2] = 0x02;
                        SendBuffer[3] = 0x1F;
                        SendBuffer[4] = 0x1F;
                        SendBuffer[5] = SumByteBot(SendBuffer.Take(5).ToArray());
                        ReadWrite(SendBuffer, 0, 6, 1);
                        // Thread.Sleep(20);
                        ReadWrite(ReadBuffer, 0, 6, 2);
                        if (ReadBuffer[0] == 0xff)
                        {
                            return true;
                        }

                    }
                    else
                    {
                        break;
                    }
                    if (sendCount == 3)
                    {
                        return false;
                    }
                }
            }
            return false;
        }
        #endregion

        private void button10_Click(object sender, EventArgs e)
        {

        }

        private void button11_Click(object sender, EventArgs e)
        {

        }
        private bool IsCancel = false;   //是否取消升级
        #region 取消升级
        private void button4_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("确定取消升级吗?", "电脑提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
            {
                Task t1 = Task.Factory.StartNew(() =>
            {
                IsCancel = true;
            });
            }
        }
        #endregion

        private void button20_Click(object sender, EventArgs e)
        {

            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (string.IsNullOrEmpty(textBox24.Text))
            {
                MessageBox.Show("请输入写入内容");
                return;
            }
            string hexStr = textBox24.Text.Trim();
            string[] Arrayhex = hexStr.Split(' ');

            for (int i = 0; i < Arrayhex.Length; i++)
            {

                SendBuffer[i] = Convert.ToByte(Arrayhex[i], 16);
            }
            ReadWrite(SendBuffer, 0, Arrayhex.Length, 1);
            Thread.Sleep(20);
            ReadWrite(ReadBuffer, 0, (int)numericUpDown2.Value, 2);
            ReceiveByte = "";
            for (int i = 0; i < (int)numericUpDown2.Value; i++)
            {
                ReceiveByte += ReadBuffer[i].ToString("X2").ToUpper() + " ";
            }
            textBox25.Text = ReceiveByte;
        }

        private void serialPort1_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
        {

        }
        string ReceiveByte = "";
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //Control.CheckForIllegalCrossThreadCalls = false;

        }

        private void serialPort1_PinChanged(object sender, System.IO.Ports.SerialPinChangedEventArgs e)
        {

        }

        private void Connected_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox8_Click(object sender, EventArgs e)
        {

        }

        private void groupBox9_Enter(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

            //if (tabControl1.SelectedIndex == 1)
            //{
            //    if (SerialState==false)
            //    {
            //        return;
            //    }
            //    SendBuffer[0] = 0x7E;
            //    SendBuffer[1] = 0x11;
            //    SendBuffer[2] = 0x00;
            //    SendBuffer[3] = 0x0F;
            //    SendBuffer[4] = 0x60;
            //    SendBuffer[5] = 0x03;
            //    // Thread.Sleep(50);
            //    byte[] a2 = new byte[34];
            //    if (ReadWrite(SendBuffer, 0, 6, 1) == false)
            //    {
            //        return ;
            //    }
            //    Thread.Sleep(100);
            //    if (ReadWrite(a2, 0, 21, 2) == false)
            //    {
            //        return ;
            //    }
            //    if (Check(a2.Skip(0).Take(19).ToArray(), a2[19]) == true)
            //    {
            //        string ddd = a2[9].ToString("x2") + a2[8].ToString("x2");
            //        string WarningInfo = Strtwo(0x00, hextoInt16(ddd), 2, 16);
            //        char[] WarnChar = WarningInfo.ToArray();
            //        #region mos管充电状态
            //        if (WarnChar[2] == '1')
            //        {
            //            pictureBoxBattery1.BackColor = Color.Red; //开
            //            pictureBox2.Visible = true;
            //            pictureBox4.Visible = false;
            //        }
            //        else
            //        {
            //            pictureBoxBattery1.BackColor = Color.Green;
            //            pictureBox2.Visible = false;
            //            pictureBox4.Visible = true;
            //        }
            //        #endregion
            //        #region mos管放电状态
            //        if (WarnChar[1] == '1')
            //        {
            //            pictureBoxBattery2.BackColor = Color.Red;//开
            //            pictureBox3.Visible = true;
            //            pictureBox1.Visible = false;
            //        }
            //        else
            //        {
            //            pictureBoxBattery2.BackColor = Color.Green;
            //            pictureBox3.Visible = false;
            //            pictureBox1.Visible = true;
            //        }
            //        #endregion
            //    }
            //}

        }

        private void button21_Click(object sender, EventArgs e)
        {
            if (button21.Text == "开始采集")
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误!");
                    return;
                }
                button21.Text = "停止采集";
                timer2.Enabled = true;
                timer2.Start();
            }
            else
            {
                timer2.Stop();
                button21.Text = "开始采集";
            }
        }
        private void DataCol()
        {
            try
            {
                byte[] writeBuffer = new byte[] { 0x10, 0x53, 0x43, 0x03 };
                ReadWrite(writeBuffer, 0, 4, 1);
                Thread.Sleep(100);
                byte[] ReadBuffer = new byte[18];
                ReadWrite(ReadBuffer, 0, 18, 2);
                int number = int.Parse(hextoInt16(ReadBuffer[2].ToString("X2") + ReadBuffer[3].ToString("X2")));
                textBox28.Text = (number * 0.01).ToString();

                number = int.Parse(hextoInt16(ReadBuffer[4].ToString("X2") + ReadBuffer[5].ToString("X2")));
                textBox33.Text = (number * 0.01).ToString();

                number = int.Parse(hextoInt16(ReadBuffer[6].ToString("X2") + ReadBuffer[7].ToString("X2")));
                textBox29.Text = (number * 0.01).ToString();

                number = int.Parse(hextoInt16(ReadBuffer[8].ToString("X2") + ReadBuffer[9].ToString("X2")));
                textBox30.Text = number.ToString();

                number = int.Parse(hextoInt16(ReadBuffer[10].ToString("X2") + ReadBuffer[11].ToString("X2")));
                textBox34.Text = number.ToString();

                textBox31.Text = ReadBuffer[12].ToString("X2") + ReadBuffer[13].ToString("X2");

                number = int.Parse(hextoInt16(ReadBuffer[14].ToString("X2") + ReadBuffer[15].ToString("X2")));
                textBox32.Text = (number * 0.01).ToString();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void label111_Click(object sender, EventArgs e)
        {

        }

        private void DateRead_Click(object sender, EventArgs e)
        {

            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x13;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x03;
                SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                SendBuffer[5] = 0x03;
                ReadWrite(SendBuffer, 0, 6, 1);
                Thread.Sleep(100);
                if (ReadWrite(ReadBuffer, 0, 9, 2) == true)
                {
                    int Year = Convert.ToInt32(ReadBuffer[4]) + 2000;
                    int Month = Convert.ToInt32(ReadBuffer[5]);
                    int Day = Convert.ToInt32(ReadBuffer[6]);
                    dateTimePicker1.Value = new DateTime(Year, Month, Day);
                }
                else
                {
                    MessageBox.Show("获取日期失败");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button23_Click(object sender, EventArgs e)
        {
            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                int Year = dateTimePicker1.Value.Year - 2000;
                int Month = dateTimePicker1.Value.Month;
                int day = dateTimePicker1.Value.Day;
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x90;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x03;
                SendBuffer[4] = Convert.ToByte(Year);
                SendBuffer[5] = Convert.ToByte(Month);
                SendBuffer[6] = Convert.ToByte(day);
                SendBuffer[7] = ReturnByte(SendBuffer.Skip(0).Take(7).ToArray(), 1);
                SendBuffer[8] = 0x03;
                ReadWrite(SendBuffer, 0, 9, 1);
                Thread.Sleep(100);
                ReadWrite(ReadBuffer, 0, 7, 2);
                if (ReadBuffer[4] == 0xAA)
                {
                    MessageBox.Show("写入成功");
                }
                else
                {
                    MessageBox.Show("写入失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #region 读取实时时间
        private void button24_Click(object sender, EventArgs e)
        {
            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x14;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x06;
                SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                SendBuffer[5] = 0x03;
                ReadWrite(SendBuffer, 0, 6, 1);
                Thread.Sleep(50);
                if (ReadWrite(ReadBuffer, 0, 12, 2) == true)
                {
                    dateTimePicker2.Value = new DateTime(ReadBuffer[4] + 2000, ReadBuffer[5], ReadBuffer[6], ReadBuffer[7], ReadBuffer[8], ReadBuffer[9]);
                }
                else
                {
                    MessageBox.Show("读取实时时间失败");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 写入实时时间
        private void button25_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误");
                return;
            }
            int Year = dateTimePicker2.Value.Year - 2000;
            int Month = dateTimePicker2.Value.Month;
            int day = dateTimePicker2.Value.Day;
            int hours = dateTimePicker2.Value.Hour;
            int minute = dateTimePicker2.Value.Minute;
            int second = dateTimePicker2.Value.Second;
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x92;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x06;
            SendBuffer[4] = Convert.ToByte(Year);
            SendBuffer[5] = Convert.ToByte(Month);
            SendBuffer[6] = Convert.ToByte(day);
            SendBuffer[7] = Convert.ToByte(hours);
            SendBuffer[8] = Convert.ToByte(minute);
            SendBuffer[9] = Convert.ToByte(second);
            SendBuffer[10] = ReturnByte(SendBuffer.Skip(0).Take(10).ToArray(), 1);
            SendBuffer[11] = 0x03;
            ReadWrite(SendBuffer, 0, 12, 1);
            Thread.Sleep(100);
            ReadWrite(ReadBuffer, 0, 8, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                MessageBox.Show("写入成功");
            }
            else
            {
                MessageBox.Show("写入失败");
            }

        }
        #endregion

        #region 获取历史数据
        private void button22_Click(object sender, EventArgs e)
        {
            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x15;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x23;
                SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                SendBuffer[5] = 0x03;
                ReadWrite(SendBuffer, 0, 6, 1);
                byte[] Data = new byte[41];
                Thread.Sleep(500);
                if (ReadWrite(Data, 0, 41, 2) == true)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    int index = dataGridView1.Rows.Add(row);
                    dataGridView1.Rows[index].Cells[0].Value = hextoInt16(Data[5].ToString("X2") + Data[4].ToString("X2"));
                    dataGridView1.Rows[index].Cells[1].Value = hextoInt16(Data[7].ToString("X2") + Data[6].ToString("X2"));
                    string Value = string.Format("{0}.{1}.{2} {3}:{4}:{5}", Data[8] + 2000, Data[9], Data[10], Data[11], Data[12], Data[13]);
                    dataGridView1.Rows[index].Cells[2].Value = Value;
                    Value = hextoInt16(Data[15].ToString("X2") + Data[14].ToString("X2"));
                    dataGridView1.Rows[index].Cells[3].Value = (int.Parse(Value) * 10).ToString();
                    Value = hextoInt16(Data[17].ToString("X2") + Data[16].ToString("X2"));
                    dataGridView1.Rows[index].Cells[4].Value = (int.Parse(Value) * 10).ToString();
                    dataGridView1.Rows[index].Cells[5].Value = hextoInt16(Data[19].ToString("X2") + Data[18].ToString("X2"));
                    dataGridView1.Rows[index].Cells[6].Value = hextoInt16(Data[21].ToString("X2") + Data[20].ToString("X2"));
                    #region 最低电压
                    dataGridView1.Rows[index].Cells[7].Value = hextoInt16(Data[23].ToString("X2") + Data[22].ToString("X2"));
                    #endregion
                    Value = hextoInt16(Data[25].ToString("X2") + Data[24].ToString("X2"));
                    dataGridView1.Rows[index].Cells[8].Value = (double.Parse(Value) / 100.00).ToString();
                    Value = hextoInt16(Data[27].ToString("X2") + Data[26].ToString("X2"));
                    dataGridView1.Rows[index].Cells[9].Value = (double.Parse(Value) / 100.00).ToString();
                    Value = hextoInt16(Data[29].ToString("X2") + Data[28].ToString("X2"));
                    dataGridView1.Rows[index].Cells[10].Value = (double.Parse(Value) / 100.00).ToString();
                    #region 状态信息 1
                    Value = Data[31].ToString("X2") + Data[30].ToString("X2");
                    string WarningInfo = Strtwo(0x00, hextoInt16(Value), 2, 16);
                    dataGridView1.Rows[index].Cells[11].Value = WarningInfo;
                    #endregion
                    #region 状态信息 2
                    Value = Data[33].ToString("X2") + Data[32].ToString("X2");
                    WarningInfo = Strtwo(0x00, hextoInt16(Value), 2, 16);
                    dataGridView1.Rows[index].Cells[12].Value = WarningInfo;
                    #endregion
                    dataGridView1.Rows[index].Cells[13].Value = Data[34];
                    dataGridView1.Rows[index].Cells[14].Value = hextoInt16(Data[36].ToString("X2") + Data[35].ToString("X2"));
                    dataGridView1.Rows[index].Cells[15].Value = hextoInt16(Data[38].ToString("X2") + Data[37].ToString("X2"));
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 获取历史最高数据
        private void button26_Click(object sender, EventArgs e)
        {
            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x16;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x14;
                SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                SendBuffer[5] = 0x03;
                ReadWrite(SendBuffer, 0, 6, 1);
                Thread.Sleep(100);
                if (ReadWrite(ReadBuffer, 0, 20, 2) == true)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    int index = dataGridView2.Rows.Add(row);
                    dataGridView2.Rows[index].Cells[0].Value = hextoInt16(ReadBuffer[5].ToString("X2") + ReadBuffer[4].ToString("X2"));
                    dataGridView2.Rows[index].Cells[1].Value = hextoInt16(ReadBuffer[7].ToString("X2") + ReadBuffer[6].ToString("X2"));
                    dataGridView2.Rows[index].Cells[2].Value = hextoInt16(ReadBuffer[9].ToString("X2") + ReadBuffer[8].ToString("X2"));
                    dataGridView2.Rows[index].Cells[3].Value = hextoInt16(ReadBuffer[11].ToString("X2") + ReadBuffer[10].ToString("X2"));
                    string Value = hextoInt16(ReadBuffer[13].ToString("X2") + ReadBuffer[12].ToString("X2"));
                    dataGridView2.Rows[index].Cells[4].Value = int.Parse(Value) * 10;
                    Value = hextoInt16(ReadBuffer[15].ToString("X2") + ReadBuffer[14].ToString("X2"));
                    dataGridView2.Rows[index].Cells[5].Value = int.Parse(Value) * 10;
                    Value = hextoInt16(ReadBuffer[17].ToString("X2") + ReadBuffer[16].ToString("X2"));
                    dataGridView2.Rows[index].Cells[6].Value = double.Parse(Value) / 100.00;
                    Value = hextoInt16(ReadBuffer[19].ToString("X2") + ReadBuffer[18].ToString("X2"));
                    dataGridView2.Rows[index].Cells[7].Value = double.Parse(Value) / 100.00;

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        #region 当前读取条数
        private void button27_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x93;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x02;
            byte[] DataByte = TenToHex((int)numericUpDown3.Value);
            SendBuffer[4] = DataByte[0];
            SendBuffer[5] = DataByte[1];
            SendBuffer[6] = ReturnByte(SendBuffer.Skip(0).Take(6).ToArray(), 1);
            SendBuffer[7] = 0x03;
            ReadWrite(SendBuffer, 0, 8, 1);
            Thread.Sleep(100);
            ReadWrite(ReadBuffer, 0, 8, 2);
            if (ReadBuffer[4] == 0xAA)
            {
                MessageBox.Show("操作成功");
            }
            else
            {
                MessageBox.Show("操作失败");
            }
        }
        #endregion

        #region 复位电量计
        private void button28_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x91;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x01;
            SendBuffer[4] = 0x55;
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1);
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            MessageBox.Show("电量计复位成功");
        }
        #endregion

        #region 清除历史最高记录
        private void button30_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x91;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x01;
            SendBuffer[4] = 0x5A;
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1);
            SendBuffer[6] = 0x03;
            if (ReadWrite(SendBuffer, 0, 7, 1) == true)
            {
                MessageBox.Show("清除历史最高数据记录成功");
            }
        }
        #endregion

        #region 清除历史数据
        private void button31_Click(object sender, EventArgs e)
        {
            if (SerialState == false)
            {
                MessageBox.Show("串口未打开");
                return;
            }
            if (BatteryState == false)
            {
                MessageBox.Show("通讯状态有误");
                return;
            }
            SendBuffer[0] = 0x7E;
            SendBuffer[1] = 0x91;
            SendBuffer[2] = 0x00;
            SendBuffer[3] = 0x01;
            SendBuffer[4] = 0xA5;
            SendBuffer[5] = ReturnByte(SendBuffer.Skip(0).Take(5).ToArray(), 1);
            SendBuffer[6] = 0x03;
            ReadWrite(SendBuffer, 0, 7, 1);
            MessageBox.Show("清除历史数据成功");
        }
        #endregion

        private void label36_Click(object sender, EventArgs e)
        {

        }

        private void groupBox6_Enter(object sender, EventArgs e)
        {

        }

        private void label61_Click(object sender, EventArgs e)
        {

        }

        private void label62_Click(object sender, EventArgs e)
        {

        }

        private void textBox_HardwareVersion_TextChanged(object sender, EventArgs e)
        {

        }

        private void label38_Click(object sender, EventArgs e)
        {

        }

        private void button29_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Execl files (*.xls)|*.xls";
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
              
                Stream myStream;
                myStream = sfd.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.Default);
                string str = "";
                try
                {
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dataGridView1.Columns[i].HeaderText;
                    }
                    sw.WriteLine(str);
                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        string tempStr = "";
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                        sw.WriteLine(tempStr);
                    }
                    sw.Close();
                    myStream.Close();
                    MessageBox.Show("保存完成");

                }
                catch (Exception ex)
                {

                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }

            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }
        #region 获取全部
        private void button32_Click(object sender, EventArgs e)
        {
            try
            {
                if (SerialState == false)
                {
                    MessageBox.Show("串口未打开");
                    return;
                }
                if (BatteryState == false)
                {
                    MessageBox.Show("通讯状态有误");
                    return;
                }
                button32.Enabled = false;
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x15;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x23;
                SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                SendBuffer[5] = 0x03;
                ReadWrite(SendBuffer, 0, 6, 1);
                Thread.Sleep(250);
                int Count = 0;
                if (ReadWrite(ReadBuffer, 0, 41, 2) == true)
                {
                    string Num = hextoInt16(ReadBuffer[5].ToString("X2") + ReadBuffer[4].ToString("X2"));
                    Count = int.Parse(Num);
                }
                SendBuffer[0] = 0x7E;
                SendBuffer[1] = 0x93;
                SendBuffer[2] = 0x00;
                SendBuffer[3] = 0x02;
                SendBuffer[4] = 01;
                SendBuffer[5] = 00;
                SendBuffer[6] = ReturnByte(SendBuffer.Skip(0).Take(6).ToArray(), 1);
                SendBuffer[7] = 0x03;
                ReadWrite(SendBuffer, 0, 8, 1);
                Thread.Sleep(100);
                ReadWrite(ReadBuffer, 0, 8, 2);
                for (int i = 0; i < Count; i++)
                {
                    if (SerialState == false)
                    {
                        break;
                    }
                    SendBuffer[0] = 0x7E;
                    SendBuffer[1] = 0x15;
                    SendBuffer[2] = 0x00;
                    SendBuffer[3] = 0x23;
                    SendBuffer[4] = ReturnByte(SendBuffer.Skip(0).Take(4).ToArray(), 1);
                    SendBuffer[5] = 0x03;
                    ReadWrite(SendBuffer, 0, 6, 1);
                    Thread.Sleep(250);
                    if (ReadWrite(ReadBuffer, 0, 41, 2) == true)
                    {
                        DataGridViewRow row = new DataGridViewRow();
                        int index = dataGridView1.Rows.Add(row);
                        dataGridView1.Rows[index].Cells[0].Value = hextoInt16(ReadBuffer[5].ToString("X2") + ReadBuffer[4].ToString("X2"));
                        dataGridView1.Rows[index].Cells[1].Value = hextoInt16(ReadBuffer[7].ToString("X2") + ReadBuffer[6].ToString("X2"));
                        string Value = string.Format("{0}.{1}.{2} {3}:{4}:{5}", ReadBuffer[8] + 2000, ReadBuffer[9], ReadBuffer[10], ReadBuffer[11], ReadBuffer[12], ReadBuffer[13]);
                        dataGridView1.Rows[index].Cells[2].Value = Value;
                        Value = hextoInt16(ReadBuffer[15].ToString("X2") + ReadBuffer[14].ToString("X2"));
                        dataGridView1.Rows[index].Cells[3].Value = (int.Parse(Value) * 10).ToString();
                        Value = hextoInt16(ReadBuffer[17].ToString("X2") + ReadBuffer[16].ToString("X2"));
                        dataGridView1.Rows[index].Cells[4].Value = (int.Parse(Value) * 10).ToString();
                        dataGridView1.Rows[index].Cells[5].Value = hextoInt16(ReadBuffer[19].ToString("X2") + ReadBuffer[18].ToString("X2"));
                        dataGridView1.Rows[index].Cells[6].Value = hextoInt16(ReadBuffer[21].ToString("X2") + ReadBuffer[20].ToString("X2"));
                        #region 最低电压
                        dataGridView1.Rows[index].Cells[7].Value = hextoInt16(ReadBuffer[23].ToString("X2") + ReadBuffer[22].ToString("X2"));
                        #endregion
                        Value = hextoInt16(ReadBuffer[25].ToString("X2") + ReadBuffer[24].ToString("X2"));
                        dataGridView1.Rows[index].Cells[8].Value = (double.Parse(Value) / 100.00).ToString();
                        Value = hextoInt16(ReadBuffer[27].ToString("X2") + ReadBuffer[26].ToString("X2"));
                        dataGridView1.Rows[index].Cells[9].Value = (double.Parse(Value) / 100.00).ToString();
                        Value = hextoInt16(ReadBuffer[29].ToString("X2") + ReadBuffer[28].ToString("X2"));
                        dataGridView1.Rows[index].Cells[10].Value = (double.Parse(Value) / 100.00).ToString();
                        #region 状态信息 1
                        Value = ReadBuffer[31].ToString("X2") + ReadBuffer[30].ToString("X2");
                        string WarningInfo = Strtwo(0x00, hextoInt16(Value), 2, 16);
                        dataGridView1.Rows[index].Cells[11].Value = WarningInfo;
                        #endregion
                        #region 状态信息 2
                        Value = ReadBuffer[33].ToString("X2") + ReadBuffer[32].ToString("X2");
                        WarningInfo = Strtwo(0x00, hextoInt16(Value), 2, 16);
                        dataGridView1.Rows[index].Cells[12].Value = WarningInfo;
                        #endregion
                        dataGridView1.Rows[index].Cells[13].Value = ReadBuffer[34];
                        dataGridView1.Rows[index].Cells[14].Value = hextoInt16(ReadBuffer[36].ToString("X2") + ReadBuffer[35].ToString("X2"));
                        dataGridView1.Rows[index].Cells[15].Value = hextoInt16(ReadBuffer[38].ToString("X2") + ReadBuffer[37].ToString("X2"));
                        Application.DoEvents();

                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                button32.Enabled = true;
            }

        }
        #endregion

        #region 获取现在时
        private void button33_Click(object sender, EventArgs e)
        {
            DateTime time = DateTime.Now;
            dateTimePicker2.Value = time;
        }
        #endregion

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControl2.SelectedIndex==0)
            {
                dataGridView1.Rows.Clear();
             
            }
            else if (tabControl2.SelectedIndex==1)
            {

                dataGridView2.Rows.Clear();
            }
        }

        #region 休眠模式
        private void button34_Click(object sender, EventArgs e)
        {
            SendBuffer[0] = 0x10;
            SendBuffer[1] = 0x55;
            SendBuffer[2] = 0x45;
            SendBuffer[3] = 0x03;
            ReadWrite(SendBuffer, 0, 4, 1);
            Thread.Sleep(100);
            MessageBox.Show("开启休眠模式");
        }
        #endregion
    }
}
